#pragma once
#include "Thread.h"
#include "RunnableTask.h"
#include "ThreadContext.h"
#include "Runtime/Log/Logger.h"
namespace Alice
{
    class PoolThreadContext : public ThreadContext
    {
    public:
        PoolThreadContext()
            : mThreadName(ENamedThreads::AnyThread)
            , mTLSSlot(0xffffffff)
            , mCompositedThread(nullptr)
        {
        }
        void Setup(ENamedThreads inThreadName, uint32 inTLSSlot, AliceAny inCompositedThread)
        {
            mThreadName = inThreadName;
            mTLSSlot = inTLSSlot;
            mCompositedThread = inCompositedThread;
        }
        void InitializeForCurrentThread()
        {
            PlatformTLS::SetTlsValue(mTLSSlot,mCompositedThread);
        }

        /** Return the index of this thread. **/
        ENamedThreads GetThreadName() const
        {
            return mThreadName;
        }
        virtual void ProcessTasksUntilQuit(int32 QueueIndex) = 0;
        virtual uint64 ProcessTasksUntilIdle(int32 QueueIndex){return 0;}
        virtual void ProcessTasksUntilManualStop(int32 QueueIndex){}
        virtual void EnqueueFromThisThread(int32 QueueIndex, RunnableTask* Task)
        {
        }
        virtual void RequestQuit(int32 QueueIndex) = 0;
        virtual bool EnqueueFromOtherThread(int32 QueueIndex, RunnableTask* Task)
        {
            return false;
        }
        virtual void WakeUp(int32 QueueIndex = 0) = 0;
        virtual bool IsProcessingTasks(int32 QueueIndex) = 0;
        virtual void Tick()
        {
            ProcessTasksUntilIdle(0);
        }
        virtual bool Init() override
        {
            InitializeForCurrentThread();
            return true;
        }
        virtual uint32 Run() override
        {
            ProcessTasksUntilQuit(0);
            //FMemory::ClearAndDisableTLSCachesOnCurrentThread();
            return 0;
        }
        virtual void Stop() override
        {
            RequestQuit(-1);
        }
        virtual void Exit() override
        {
        }
    protected:
        ENamedThreads										mThreadName;
        uint32												mTLSSlot;
        ThreadSafeCounter									mIsStalled;
        /** Array of tasks for this task thread. */
        std::vector<RunnableTask*>                          mNewTasks;
        AliceAny                                            mCompositedThread;
    };
}